//
//  ViewController.m
//  Test
//
//  Created by geng on 2019/7/24.
//  Copyright © 2019 geng. All rights reserved.
//

#define KSCRW   [UIScreen mainScreen].bounds.size.width
#define KSCRH   [UIScreen mainScreen].bounds.size.height
#define NavH    (KSCRH>=812 ? 88.:64.)

#import "ViewController.h"
#import "HTTPServer.h"
#import <WebKit/WebKit.h>
#import "AppDelegate.h"
#import<AdSupport/AdSupport.h>
#import "DeviceParam.h"
#import "base64.h"
#import "BGLocationConfig.h"
#import "GHTTPConnection.h"

#import <ifaddrs.h>
#import <resolv.h>
#import <arpa/inet.h>
#import <net/if.h>
#import <netdb.h>
#import <netinet/ip.h>
#import <net/ethernet.h>
#import <net/if_dl.h>
#import "WeChatManager.h"
#import "LMAppController.h"
#import "HTTPServer.h"

#import <StoreKit/StoreKit.h>
#import <SafariServices/SafariServices.h>
#define MDNS_PORT       5353
#define QUERY_NAME      "_apple-mobdev2._tcp.local"
#define DUMMY_MAC_ADDR  @"02:00:00:00:00:00"
#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"


#define WIDTH   ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT  ([UIScreen mainScreen].bounds.size.height)

@interface ViewController ()<WKNavigationDelegate,SKStoreProductViewControllerDelegate>

@property (nonatomic,strong) HTTPServer *localHttpServer;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, copy) NSString *urlStr;
@property (nonatomic, assign) BOOL loadHttpSuc;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    UIImageView *bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg"]];
    [self.view addSubview:bg];
    bg.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    self.view.backgroundColor = [UIColor colorWithRed:0.1 green:0.14 blue:0.19 alpha:1];
    // Do any additional setup after loading the view, typically from a nib.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
//    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"LocalHttp" style:UIBarButtonItemStylePlain target:self action:@selector(loadLocalHttpServer)]];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onHandler) name:@"OPEN_APPSTORE" object:nil];
    
    
    
    
    
    UILabel * lb1 = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT-180, WIDTH, 32)];
    lb1.text = @"芝麻试玩";
    lb1.textColor = UIColor.blackColor;
    lb1.textAlignment = NSTextAlignmentCenter;
    lb1.font = [UIFont boldSystemFontOfSize:30];
    [self.view addSubview:lb1];
    
    UILabel * lb3 = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT-140, WIDTH, 26)];
    lb3.text = @"赚零花钱，就上芝麻试玩";
    lb3.textColor = UIColor.grayColor;
    lb3.textAlignment = NSTextAlignmentCenter;
    lb3.font = [UIFont systemFontOfSize:24];
    [self.view addSubview:lb3];
    
    
    UIButton *startBtn = [[UIButton alloc] initWithFrame:CGRectMake((WIDTH-200)*.5, HEIGHT-90, 200, 50)];
    startBtn.backgroundColor = UIColor.redColor;
    [startBtn setTitle:@"开始赚钱" forState:UIControlStateNormal];
    [startBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    startBtn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    startBtn.layer.cornerRadius = 25;
    [self.view addSubview:startBtn];
    [startBtn addTarget:self action:@selector(loadLocalHttpServer) forControlEvents:UIControlEventTouchUpInside];
    
//    UILabel * lb2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200 - 30, 50)];
//    lb2.text = @"开始赚钱";
//    lb2.textColor = UIColor.whiteColor;
//    lb2.textAlignment = NSTextAlignmentCenter;
//    lb2.font = [UIFont boldSystemFontOfSize:20];
//    [startBtn addSubview:lb2];
    
//    UIImageView *right = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right"]];
//    [startBtn addSubview:right];
//    right.frame = CGRectMake(150,13, 24, 24);
    
//    lb1.frame = CGRectMake(0, HEIGHT - 130, WIDTH, 30);
//    [self getParam];

//    NSString *string = @"{\"category\":\"1\",\"page\":\"1\",\"limit\":\"20\", \"baseParam\":\"{\\\"uid\\\":\\\"19\\\",\\\"deviceId\\\":\\\"077b9e644c561251\\\",\\\"token\\\":\\\"dbc4ee1bd0ca4197a7ff900e86b9aff8\\\",\\\"url\\\":\\\"http://mobile.51ykh.com:8282/sesameplay/mobile/api/getTaskList.do\\\"}\"}";

    
//    NSString * context = __BASE64(string);
//    [self request:context];
    NSString *isbreak = [DeviceParam getIsBreak];
    if ([isbreak isEqualToString:@"1"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的手机已越狱，无法继续使用本应用" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            exit(0);
        }]];
//        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        // 弹出对话框
        [self presentViewController:alert animated:true completion:nil];
        return;
    }
    
    NSString *isVPN = [DeviceParam getIsVPN];
    if ([isVPN isEqualToString:@"1"]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请关闭VPN功能，然后重启本应用" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            exit(0);
        }]];
        // 弹出对话框
        [self presentViewController:alert animated:true completion:nil];
        return;
    }
    [self performSelector:@selector(configLocalHttpServer) withObject:nil afterDelay:1];
    [BGLocationConfig starBGLocation];
    [self.timer fire];
}

- (void)onHandler{
    NSLog(@"onHandler");
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/search?"]];
    
}
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)onStartHandler{
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveUserInfo:) name:@"receiveUserInfo" object:nil];
//
//    [WeChatManager sendAuthRequest];
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/search?"]];
    
}
- (void)receiveUserInfo:(NSNotification *) notification{
    NSLog(@"notification.object  %@", notification.object);
}

- (BOOL)loadLocalHttpServer{
    
//    AppDelegate *appd = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    NSString *port = appd.port;
//    if (nil == port) {
//        NSLog(@">>> Error:端口不存在");
//        return NO;
//    }
    
    NSURL *url = [NSURL URLWithString:self.urlStr];
    [[UIApplication sharedApplication]openURL:url];
    
    return YES;
}

- (NSString *)urlStr{
    if (nil == _urlStr) {
        _urlStr = @"http://test.51ykh.com:8991/dist";
//        _urlStr = @"http://localhost:56766/getSysInfo.do";
    }
    return _urlStr;
}


-(void)dealloc{
    //移除所有观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark -- 本地服务器 --
#pragma mark -服务器
#pragma mark - 搭建本地服务器 并且启动
- (void)configLocalHttpServer{
    _localHttpServer = [[HTTPServer alloc] init];
    [_localHttpServer setType:@"_http.tcp"];
    [_localHttpServer setConnectionClass:[GHTTPConnection class]];
    [_localHttpServer setPort:56766];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Web"];
    NSLog(@">>>>[WebFilePath:]%@",webPath);
    
    
    if (![fileManager fileExistsAtPath:webPath]){
        NSLog(@">>>> File path error!");
    }else{
        NSString *webLocalPath = webPath;
        [_localHttpServer setDocumentRoot:webLocalPath];
        NSLog(@">>webLocalPath:%@",webLocalPath);
        [self startServer];
    }
    
    
}

- (void)startServer
{
    NSError *error;
    if([_localHttpServer start:&error]){
        NSLog(@"Started HTTP Server on port %hu", [_localHttpServer listeningPort]);
//        self.port = [NSString stringWithFormat:@"%d",[_localHttpServer listeningPort]];
        
        NSString *ipStr = [self getIpAddresses];
        NSLog(@"ip地址 %@", ipStr);
    }
    else{
        NSLog(@"Error starting HTTP Server: %@", error);
    }
}
- (NSTimer *)timer{
    if (nil == _timer) {
        _timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//            NSLog(@"运行ing");
        }];
        NSRunLoop *curRun = [NSRunLoop currentRunLoop];
        [curRun addTimer:_timer forMode:NSRunLoopCommonModes];
        
    }
    return _timer;
}
- (NSString *)getIpAddresses{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}
@end
